package com.buss.FrontController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.dao.jdbc.JdbcDao;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.service.CommonService;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.buss.articlegroup.service.ArticleGroupInfoServiceI;
import com.buss.message.entity.BnsMessageEntity;
import com.buss.user.entity.BnsUserFriendEntity;
import com.buss.user.entity.BnsUsersInfoEntity;
import com.buss.user.service.BnsUserFriendServiceI;

/**
 * @Title: Controller
 * @Description: 好友控制层
 * @author hlg
 * @date 2016-10-08
 * @version V1.0
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/FriendController")
public class FriendController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(FriendController.class);

	@Autowired
	private ArticleGroupInfoServiceI articleGroupInfoService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private JdbcDao jdbcDao;
	@Autowired
	private CommonService commonService;
	@Autowired
	private BnsUserFriendServiceI bnsUserFriendService;

	private String message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	/**
	 * 用户好友列表
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "friendLists")
	public ModelAndView friendLists(Model model, HttpServletRequest request) {
		HttpSession session = request.getSession();
		BnsUsersInfoEntity userInfo = (BnsUsersInfoEntity) session.getAttribute("LOCAL_FRONT_USER");
		if (!StringUtil.isNotEmpty(userInfo)) {
			return new ModelAndView("front/login");
		}
		
		Long dataCount = 0L;
		int pageParam = 1;
		String page = request.getParameter("page");
		if (StringUtil.isEmpty(page)) {
			pageParam = 1;
		} else {
			pageParam = Integer.parseInt(page);
		}
		int mbId = userInfo.getUserId();
		dataCount = systemService.getCountForJdbcParam("select count(1) from bns_user_friend where user_id='" + mbId + "'", null);
		
		String sql = "SELECT w.id,w.friend_id,a.user_id,a.user_name,a.headerimg,a.signature from bns_user_friend w LEFT JOIN bns_users_info a on w.friend_id = a.user_id where w.user_id='"+ mbId+ "'";	
		List<Map<String,Object>> listsFriend = systemService.findForJdbc(sql, pageParam, 10);
		
		int pageCount = 0;
		if (dataCount.intValue() > 0 && dataCount.intValue() % 10 == 0) {
			pageCount = dataCount.intValue() / 10;
		} else {
			pageCount = dataCount.intValue() / 10 + 1;
		}
		
		model.addAttribute("pageCount", pageCount);
		model.addAttribute("listsFriend", listsFriend);
		model.addAttribute("backType", "friendLists");
		return new ModelAndView("front/friendLists");
	}
	
	/**
	 * 删除好友
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params = "delBuddy")
	public ModelAndView delBuddy(Model model,HttpServletRequest request){
		HttpSession session = request.getSession();
		AjaxJson j = new AjaxJson();
		BnsUsersInfoEntity userInfo = (BnsUsersInfoEntity) session.getAttribute("LOCAL_FRONT_USER");
		if (!StringUtil.isNotEmpty(userInfo)) {
			return new ModelAndView("front/login");
		}
		
		String[] selectDeleteId = request.getParameterValues("info");
		for (int i = 0; i < selectDeleteId.length; i++) {
//			sqlDelete[i] = " delete from bns_user_friend w where w.id='"+selectDeleteId[i]+ "'";
//			sql = "delete from bns_user_friend w where w.user_id='"+userInfo.getUserId()+ "' and w.friend_id="+selectDeleteId[i];
			systemService.deleteEntityById(BnsUserFriendEntity.class, selectDeleteId[i]);
//			executeSql(sql);
		}
//		int n=jdbcDao.batchUpdateSqlArr(sqlDelete); 
		model.addAttribute("message", "删除成功");
		return new ModelAndView("redirect:/FriendController.do?friendLists");
	}
	
	
	/**
	 * 附近的人
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "nearManLists")
	public ModelAndView nearManLists(Model model, HttpServletRequest request) {
		
		model.addAttribute("backType", "nearManLists");
		return new ModelAndView("front/nearManLists");
	}
	
	/**
	 * 我的访客
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "guestLists")
	public ModelAndView guestLists(Model model, HttpServletRequest request) {
		
		model.addAttribute("backType", "guestLists");
		return new ModelAndView("front/guestLists");
	}
	
	/**
	 * 足迹列表
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "trackLists")
	public ModelAndView trackLists(Model model, HttpServletRequest request) {
		model.addAttribute("backType", "trackLists");
		return new ModelAndView("front/trackLists");
	}
	/**
	 * 黑名单
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "blackList")
	public ModelAndView blackList(Model model, HttpServletRequest request) {
		model.addAttribute("backType", "blackList");
		return new ModelAndView("front/blackList");
	}
	
	
	/**
	 * 查找好友
	 * 查找男女朋友
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "searchNnFirend")
	public ModelAndView searchNnFirend(Model model, HttpServletRequest request) {
		model.addAttribute("list", "no");
		model.addAttribute("backType", "searchNnFirend");
		return new ModelAndView("front/searchNnFirend");
	}
	
	
	/**
	 * 查找同城的人
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "searchTcFirend")
	public ModelAndView searchTcFirend(Model model, HttpServletRequest request) {
		model.addAttribute("list", "no");
		model.addAttribute("backType", "searchTcFirend");
		return new ModelAndView("front/searchTcFirend");
	}
	
	/**
	 * 查找老乡
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "searchLxFirend")
	public ModelAndView searchLxFirend(Model model, HttpServletRequest request) {
		model.addAttribute("list", "no");
		model.addAttribute("backType", "searchLxFirend");
		return new ModelAndView("front/searchLxFirend");
	}
	
	/**
	 * 查找同年同月同日生的人
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "searchTnTyFirend")
	public ModelAndView searchTnTyFirend(Model model, HttpServletRequest request) {
		model.addAttribute("list", "no");
		model.addAttribute("backType", "searchTnTyFirend");
		return new ModelAndView("front/searchTnTyFirend");
	}
	
	
	
	
	/**
	 * 高级方式查找
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "gjSearchFirend")
	public ModelAndView gjSearchFirend(Model model, HttpServletRequest request) {
		model.addAttribute("list", "no");
		model.addAttribute("backType", "gjSearchFirend");
		return new ModelAndView("front/gjSearchFirend");
	}
	/**
	 * 高级方式查找
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "gjSearchFirendResult")
	public ModelAndView gjSearchFirendResult(Model model, HttpServletRequest request) {
		String searchType = request.getParameter("searchType");	//查找类型
		
		String userName = request.getParameter("userName");
		String userId = request.getParameter("userId");
		String sex = request.getParameter("sex");
		String age1 = request.getParameter("age1");
		String age2 = request.getParameter("age2");
		String isUpHeadImg = request.getParameter("isUpHeadImg");
		
		String year = request.getParameter("year");
		String month = request.getParameter("month");
		String date = request.getParameter("date");
		
		//居住省市区
		String jz_provinces = request.getParameter("jz_provinces");
		String jz_city = request.getParameter("jz_city");
		String jz_county = request.getParameter("jz_county");
		String jz_village = request.getParameter("jz_village");
		//出生省市区
		String cs_provinces = request.getParameter("cs_provinces");
		String cs_city = request.getParameter("cs_city");
		String cs_county = request.getParameter("cs_county");
		String cs_village = request.getParameter("cs_village");
		
		
		Map<String,String> map = new HashMap<String, String>();
		
		map.put("userName", userName);
		map.put("userId", userId); 
		map.put("sex", sex);
		map.put("age1", age1);
		map.put("age2", age2);
		map.put("isUpHeadImg", isUpHeadImg);
		
		if(StringUtil.isNotEmpty(year)){
			map.put("birthday", year+"-"+month+"-"+date); 
		}
		if(StringUtil.isNotEmpty(jz_provinces)){
			map.put("abode", jz_provinces+jz_city+jz_county+jz_village);
		}
		if(StringUtil.isNotEmpty(cs_provinces)){
			map.put("address", cs_provinces+cs_city+cs_county+cs_village);
		}
		
		List<Map<String, Object>> listsFriends = bnsUserFriendService.searchFriendLists(map);
		
		model.addAttribute("list", "yes");
		
		String path = "front/gjSearchFirend";
		String backType = "gjSearchFirend";
		if(searchType.equals("searchNn")){
			path = "front/searchNnFirend";
			backType = "searchNnFirend";
		}
		if(searchType.equals("searchTc")){
			path = "front/searchTcFirend";
			backType = "searchTcFirend";
		}
		if(searchType.equals("searchLx")){
			path = "front/searchLxFirend";
		}
		if(searchType.equals("searchTnTy")){
			path = "front/searchTnTyFirend";
			backType = "searchTnTyFirend";
		}
		if(listsFriends.size() == 0){
			model.addAttribute("list", "no");
			path = "front/gjSearchFirend";
			backType = "gjSearchFirend";
		}
		
		model.addAttribute("listsFriend", listsFriends);
		model.addAttribute("backType", backType);
		return new ModelAndView(path);
	}
	
	
	
	/**
	 * 可能认识的人
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "maybeKnowFirend")
	public ModelAndView maybeKnowFirend(Model model, HttpServletRequest request) {
		HttpSession session = request.getSession();
		BnsUsersInfoEntity userInfo = (BnsUsersInfoEntity) session.getAttribute("LOCAL_FRONT_USER");
		if (!StringUtil.isNotEmpty(userInfo)) {
			return new ModelAndView("front/login");
		}
		int x=(int)(Math.random()*100);
		int userId = userInfo.getUserId();
		StringBuffer id = new StringBuffer();
		//随机生成
		for(int i = 1; i<x; i++){
			userId +=i;
			id.append(userId);
			id.append(",");
		}
		id.deleteCharAt(id.length()-1); 
		
//		String sql = "select * from bns_users_info where user_id in ("+id+")";
		String sql = "select * from bns_users_info ";
		List<Map<String, Object>> maybeKnowFirendList = bnsUserFriendService.findForJdbc(sql);
		
		model.addAttribute("maybeKnowFirendList", maybeKnowFirendList);
		model.addAttribute("backType", "maybeKnowFirend");
		return new ModelAndView("front/maybeKnowFirend");
	}
	
	/**
	 * 添加好友页面跳转
	 */
	@RequestMapping(params = "goAddBuddy")
	public ModelAndView goAddBuddy(HttpServletRequest request, HttpServletResponse response){
		HttpSession session = request.getSession();
		BnsUsersInfoEntity userInfo = (BnsUsersInfoEntity) session.getAttribute("LOCAL_FRONT_USER");
		if (!StringUtil.isNotEmpty(userInfo)) {
			return new ModelAndView("front/login");
		}
		
		String addType = request.getParameter("addType");	//加好友类型
		String path = "";
		if(addType.equals("apply")){
			path = "front/applyBuddy";
		}
		if(addType.equals("pass")){
			path = "front/addBuddy";
		}
		
		String userId = request.getParameter("userId");
		String userName = request.getParameter("userName");
		request.setAttribute("userId",userId);
		request.setAttribute("userName",userName);
		
		return new ModelAndView(path);
	}
	
	/**
	 * 添加好友
	 */
	@ResponseBody
	@RequestMapping(params = "addBuddy")
	public AjaxJson addBuddy(HttpServletRequest request, HttpServletResponse response){
		HttpSession session = request.getSession();
		AjaxJson j = new AjaxJson();
		BnsUsersInfoEntity userInfo = (BnsUsersInfoEntity) session.getAttribute("LOCAL_FRONT_USER");
		if (!StringUtil.isNotEmpty(userInfo)) {
			j.setMsg("请登录");
			return j;
		}
		int myId = userInfo.getUserId();
		String addType = request.getParameter("addType");	//加好友类型
		
		int isGre = 0; 	//请求好友
		String messageTitle = "好友申请";
		String messageContent = "请求添加您为好友！";
		if(addType.equals("pass")){	//好友请求 通过
			isGre = 1;
			messageTitle = "同意";
			messageContent = "同意添加您为好友！";
		}
		if(addType.equals("refused")){	//好友请求 拒绝
			isGre = 2;
			messageTitle = "拒绝";
			messageContent = "拒绝添加您为好友！";
		}
		
		String fuserIdv = request.getParameter("userId");
		String fFz = request.getParameter("fFz");	//分组	XXX 分组是否需要字典???
		String fy = request.getParameter("fy");	//附言
		int fuserId = Integer.valueOf(fuserIdv);
		String userName = request.getParameter("userName");
		
		BnsUserFriendEntity uFriend = new BnsUserFriendEntity();
		uFriend.setCreateDate(new Date());
		uFriend.setUserId(myId);
		uFriend.setFriendId(fuserId);
		uFriend.setFz(fFz);
		uFriend.setFy(fy);
		uFriend.setIsGre(isGre);
		bnsUserFriendService.save(uFriend);
		//第二条好友记录（用户id和好友id相反，便于好友关系的查询） --zyb
		BnsUserFriendEntity uFriend2 = new BnsUserFriendEntity();
		uFriend2.setCreateDate(new Date());
		uFriend2.setUserId(fuserId);
		uFriend2.setFriendId(myId);
		uFriend2.setFz(fFz);
		uFriend2.setFy(fy);
		uFriend2.setIsGre(isGre);
		bnsUserFriendService.save(uFriend2);
		//添加一条消息
		BnsMessageEntity fMsg = new BnsMessageEntity();
		fMsg.setTitle(messageTitle);
		fMsg.setCreateBy(""+myId);
		fMsg.setCreateName(userInfo.getUserName());
		fMsg.setReceiveId(fuserIdv);
		fMsg.setMessageTypes(3);
		fMsg.setContent(userName+messageContent);
		fMsg.setCreateDate(new Date());
		fMsg.setIsRead("N");
		fMsg.setStates("Y");
		commonService.save(fMsg);
		
		// XXX 需要前台提示 已添加为好友 或者别的动作的消息提示
//		int n=jdbcDao.batchUpdateSqlArr(sqlArr);  //回滚事物
		j.setMsg("添加成功");
		j.setSuccess(true);
		return j;
	}
	
	/**
	 * 好友请求list
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "firendRequest")
	public ModelAndView firendRequest(Model model, HttpServletRequest request) {
		HttpSession session = request.getSession();
		BnsUsersInfoEntity userInfo = (BnsUsersInfoEntity) session.getAttribute("LOCAL_FRONT_USER");
		if (!StringUtil.isNotEmpty(userInfo)) {
			return new ModelAndView("front/login");
		}
		int userId = userInfo.getUserId();
		
		String sql = "SELECT w.friend_id,a.user_id,a.user_name,a.headerimg,a.signature,w.create_date "
				+ "from bns_user_friend w LEFT JOIN bns_users_info a on w.friend_id = a.user_id where w.is_gre=0 and w.user_id = '"+ userId	+ "'";
		List<Map<String, Object>> requestFirendList = bnsUserFriendService.findForJdbc(sql);
		
		model.addAttribute("requestFirendList", requestFirendList);
		model.addAttribute("backType", "firendRequest");
		return new ModelAndView("front/firendRequest");
	}
	
	/**
	 * 好友分组
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "firendGroup")
	public ModelAndView firendGroup(Model model, HttpServletRequest request) {
		HttpSession session = request.getSession();
		BnsUsersInfoEntity userInfo = (BnsUsersInfoEntity) session.getAttribute("LOCAL_FRONT_USER");
		if (!StringUtil.isNotEmpty(userInfo)) {
			return new ModelAndView("front/login");
		}
		Long dataCount = 0L;
		int pageParam = 1;
		String page = request.getParameter("page");
		String fzType = request.getParameter("fzType");
		
		
		if (StringUtil.isEmpty(page)) {
			pageParam = 1;
		} else {
			pageParam = Integer.parseInt(page);
		}
		
		
		
		int mbId = userInfo.getUserId();
		dataCount = systemService.getCountForJdbcParam("select count(1) from bns_user_friend where user_id='" + mbId + "'", null);
		
		String sql = "SELECT w.friend_id,a.user_id,a.user_name,a.headerimg,a.signature,w.fz from bns_user_friend w LEFT JOIN bns_users_info a on w.friend_id = a.user_id where w.user_id='"+ mbId+ "'";
		if(!fzType.equals("all")){
			sql += " and w.fz='"+fzType+"'";
		}
		List<Map<String,Object>> listsFriend = systemService.findForJdbc(sql, pageParam, 10);
		
		int pageCount = 0;
		if (dataCount.intValue() > 0 && dataCount.intValue() % 10 == 0) {
			pageCount = dataCount.intValue() / 10;
		} else {
			pageCount = dataCount.intValue() / 10 + 1;
		}
		
		model.addAttribute("pageCount", pageCount);
		model.addAttribute("listsFriend", listsFriend);
		model.addAttribute("backType", "firendGroup");
		return new ModelAndView("front/firendGroup");
	}
	
	/**
	 * 设置好友分组
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "setFirendGroup")
	public ModelAndView setFirendGroup(Model model, HttpServletRequest request) {
		String fz = request.getParameter("fz");
		String[] selectId = request.getParameterValues("info");
		String[] sql= new String[selectId.length];
		for (int i = 0; i < selectId.length; i++) {
			sql[i] = " update bns_user_friend w set w.fz='"+fz+ "'  where w.friend_id="+selectId[i];
		}
		int n=jdbcDao.batchUpdateSqlArr(sql); 
		return new ModelAndView("front/firendGroup");
	}
	

}
